package com.tanhua.dubbo.api;

import com.tanhua.dubbo.utils.IdWorker;
import com.tanhua.model.mongo.PeachBlossom;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

@DubboService
public class PeachBlossomApiImpl implements PeachBlossomApi {
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private IdWorker idWorker;
    @Override
    /**
     * 桃花传音-发送语音
     */
    public void send(PeachBlossom peachBlossom) {
        peachBlossom.setId(ObjectId.get());
        //因为mongodb单独保存key-value形式的数据,所以自增id字段只能以文档(集合)形式保存,所以随便给一个key做标识即可
        peachBlossom.setSid(idWorker.getNextId("peachBlossom"));
        mongoTemplate.save(peachBlossom);


    }

    /**
     * 查询一条语音
     * @param userId
     * @return
     */
    @Override
    public PeachBlossom findVoice(long userId) {
        Query query = new Query(Criteria.where("userId").is(userId))
                .with(Sort.by(Sort.Order.desc("created")));
        if (query != null){
            return mongoTemplate.findOne(query,PeachBlossom.class);
        }

        return null;
    }
}
